package cn.exrick.xboot.modules.activiti.controller;

import cn.exrick.xboot.common.constant.ActivitiConstant;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.SecurityUtil;
import cn.exrick.xboot.common.utils.SnowFlakeUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.modules.activiti.dao.mapper.EventReportMapper;
import cn.exrick.xboot.modules.activiti.entity.ActBusiness;
import cn.exrick.xboot.modules.activiti.entity.ActProcess;
import cn.exrick.xboot.modules.activiti.entity.business.EventReport;
import cn.exrick.xboot.modules.activiti.service.ActBusinessService;
import cn.exrick.xboot.modules.activiti.service.ActProcessService;
import cn.exrick.xboot.modules.activiti.service.business.EventReportService;
import cn.exrick.xboot.modules.activiti.service.mybatis.IActService;
import cn.exrick.xboot.modules.activiti.service.mybatis.IHistoryIdentityService;
import cn.exrick.xboot.modules.activiti.utils.MessageUtil;
import cn.exrick.xboot.modules.activiti.vo.ActPage;
import cn.exrick.xboot.modules.activiti.vo.Assignee;
import cn.exrick.xboot.modules.activiti.vo.HistoricTaskVo;
import cn.exrick.xboot.modules.activiti.vo.TaskVo;
import cn.exrick.xboot.modules.base.entity.Department;
import cn.exrick.xboot.modules.base.entity.Role;
import cn.exrick.xboot.modules.base.entity.User;
import cn.exrick.xboot.modules.base.service.RoleService;
import cn.exrick.xboot.modules.base.service.UserService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricIdentityLink;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Exrick
 */
@Slf4j
@RestController
@Api(description = "任务管理接口")
@RequestMapping("/xboot/actTask")
@Transactional
public class ActTaskController {

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ManagementService managementService;

    @Autowired
    private ActProcessService actProcessService;

    @Autowired
    private ActBusinessService actBusinessService;

    @Autowired
    private EventReportService eventReportService;

    @Autowired
    private EventReportMapper eventReportMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private IHistoryIdentityService iHistoryIdentityService;

    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private MessageUtil messageUtil;

    @Autowired
    private IActService iActService;

    @RequestMapping(value = "/todoList", method = RequestMethod.GET)
    @ApiOperation(value = "代办列表")
    public Result<Object> todoList(@RequestParam(required = false) String name,
                                   @RequestParam(required = false) String depId,
                                   @RequestParam(required = false) String categoryId,
                                   @RequestParam(required = false) Integer priority,
                                   @RequestParam(required = false) String key,
                                   @RequestParam(required = false) String locality,
                                   @RequestParam(required = false) String eventDescribe,
                                   @RequestParam(required = false) String eventType,
                                   @RequestParam(required = false) String eventNum,
                                   @ModelAttribute SearchVo searchVo,
                                   @ModelAttribute PageVo pageVo){

        ActPage<TaskVo> page = new ActPage<TaskVo>();
        List<TaskVo> list = new ArrayList<>();

        String userId = securityUtil.getCurrUser().getId();
        TaskQuery query = taskService.createTaskQuery().taskCandidateOrAssigned(userId);

        // 多条件搜索
        if("createTime".equals(pageVo.getSort())&&"asc".equals(pageVo.getOrder())){
            query.orderByTaskCreateTime().asc();
        }else if("priority".equals(pageVo.getSort())&&"asc".equals(pageVo.getOrder())){
            query.orderByTaskPriority().asc();
        }else if("priority".equals(pageVo.getSort())&&"desc".equals(pageVo.getOrder())){
            query.orderByTaskPriority().desc();
        }else{
            query.orderByTaskCreateTime().desc();
        }

        if(StrUtil.isNotBlank(categoryId)){
            query.taskCategory(categoryId);
        }
        if(priority!=null){
            query.taskPriority(priority);
        }
        if(StrUtil.isNotBlank(key)) {
            query.processDefinitionKey(key);
        }
        if(StrUtil.isNotBlank(searchVo.getStartDate())||StrUtil.isNotBlank(searchVo.getEndDate())){
            if(StrUtil.isNotBlank(searchVo.getStartDate())){
                Date start = DateUtil.parse(searchVo.getStartDate());
                query.taskCreatedAfter(start);
            }
            if (StrUtil.isNotBlank(searchVo.getEndDate())){
                Date end = DateUtil.parse(searchVo.getEndDate());
                query.taskCreatedBefore(DateUtil.endOfDay(end));
            }
        }else {
            Date da = new Date();//获取当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(da);//把当前时间赋给日历
            calendar.add(calendar.MONTH, -2); //设置为前2月 MONTH DAY_OF_MONTH
            da = calendar.getTime();//获取2个月前的时间
            query.taskCreatedAfter(DateUtil.endOfDay(da));
        }

        List<Task> taskLists =  query.list();
        List<Task> taskInstances1 =  new ArrayList<>();
        if(StrUtil.isNotBlank(depId)){
            for(int i = 0;i<taskLists.size();i++){
                TaskVo htv = new TaskVo(taskLists.get(i));
                List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForProcessInstance(htv.getProcInstId());
                for(HistoricIdentityLink hik : identityLinks){
                    // 关联发起人
                    if("starter".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                        try {
                            if(depId.equals(userService.get(hik.getUserId()).getDepartmentId())){
                                taskInstances1.add(taskLists.get(i));
                            }
                        }catch (Exception e1){}

                    }
                }
            }
        }else{
            taskInstances1 = taskLists;
        }
        List<Task> taskInstances =  new ArrayList<>();
        if(StrUtil.isNotBlank(name)){
            for(int i = 0;i<taskInstances1.size();i++){
                TaskVo htv = new TaskVo(taskInstances1.get(i));
                List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForProcessInstance(htv.getProcInstId());
                for(HistoricIdentityLink hik : identityLinks){
                    // 关联发起人
                    if("starter".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                        try {
                            if(userService.get(hik.getUserId()).getUsername().contains(name)){
                                taskInstances.add(taskInstances1.get(i));
                            }
                        }catch (Exception e1){}

                    }
                }
            }
        }else{
            taskInstances = taskInstances1;
        }
        List<Task> localityStr =  new ArrayList<>();
        if(StrUtil.isNotBlank(locality)){
            for (int i=0;i<taskInstances.size();i++){
                TaskVo tv = new TaskVo(taskInstances.get(i));
                ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(tv.getProcInstId()).singleResult();
                tv.setBusinessKey(pi.getBusinessKey());
                ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
                if(actBusiness!=null){
                    tv.setTableId(actBusiness.getTableId());
                    EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                    if(eventReport!=null &&eventReport.getLocality() !=null&&eventReport.getLocality() != ""){
                        if (eventReport.getLocality().contains(locality)){
                            localityStr.add(taskInstances.get(i));
                        }
                    }
                }
            }
        }else {
            localityStr = taskInstances;
        }
        List<Task> eventNumStr =  new ArrayList<>();
        if (StrUtil.isNotBlank(eventNum)){
            for(int i=0;i<localityStr.size();i++){
                TaskVo tv = new TaskVo(localityStr.get(i));
                ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(tv.getProcInstId()).singleResult();
                tv.setBusinessKey(pi.getBusinessKey());
                ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
                if(actBusiness!=null){
                    tv.setTableId(actBusiness.getTableId());
                    EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                    if(eventReport!=null &&eventReport.getEventNum() !=null&&eventReport.getEventNum() != ""){
                        if (eventReport.getEventNum().contains(eventNum)){
                            eventNumStr.add(localityStr.get(i));
                        }
                    }
                }
            }
        }else {
            eventNumStr = localityStr;
        }

        List<Task> eventTypeStr = new ArrayList<>();

        if (StrUtil.isNotBlank(eventType)){
            for (int i=0;i<eventNumStr.size();i++){
                TaskVo tv = new TaskVo(eventNumStr.get(i));
                ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(tv.getProcInstId()).singleResult();
                tv.setBusinessKey(pi.getBusinessKey());
                ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
                if(actBusiness!=null){
                    tv.setTableId(actBusiness.getTableId());
                    EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                    if(eventReport!=null &&eventReport.getEventType() !=null&&eventReport.getEventType() != ""){
                        if (eventReport.getEventType().equals(eventType)){
                            eventTypeStr.add(eventNumStr.get(i));
                        }
                    }
                }
            }
        }else {
            eventTypeStr = eventNumStr;
        }

        List<Task> eventDescribeStr = new ArrayList<>();

        if(StrUtil.isNotBlank(eventDescribe)){
            for (int i=0;i<eventTypeStr.size();i++){
                TaskVo tv = new TaskVo(eventTypeStr.get(i));
                ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(tv.getProcInstId()).singleResult();
                tv.setBusinessKey(pi.getBusinessKey());
                ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
                if(actBusiness!=null){
                    tv.setTableId(actBusiness.getTableId());
                    EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                    if(eventReport!=null &&eventReport.getEventDescribe() !=null&&eventReport.getEventDescribe() != ""){
                        if (eventReport.getEventDescribe().contains(eventDescribe)){
                            eventDescribeStr.add(eventTypeStr.get(i));
                        }
                    }
                }
            }
        }else {
            eventDescribeStr = eventTypeStr;
        }

        page.setTotalElements((long) eventDescribeStr.size());
        int first =  (pageVo.getPageNumber()-1) * pageVo.getPageSize();
        int end = eventDescribeStr.size();
        if((first+pageVo.getPageSize())<end){
            end = first+pageVo.getPageSize();
        }
        List<Task> taskList = eventDescribeStr.subList(first,end);

        /*page.setTotalElements(query.count());
        int first =  (pageVo.getPageNumber()-1) * pageVo.getPageSize();
        List<Task> taskList = query.listPage(first, pageVo.getPageSize());*/

        // 转换vo
        taskList.forEach(e -> {
            TaskVo tv = new TaskVo(e);

            // 关联委托人
            if(StrUtil.isNotBlank(tv.getOwner())){
                tv.setOwner(userService.get(tv.getOwner()).getUsername());
            }
            List<IdentityLink> identityLinks = runtimeService.getIdentityLinksForProcessInstance(tv.getProcInstId());
            for(IdentityLink ik : identityLinks){
                // 关联发起人
                if("starter".equals(ik.getType())&&StrUtil.isNotBlank(ik.getUserId())){
                    try {
                        tv.setApplyer(userService.get(ik.getUserId()).getUsername());
                    }catch (Exception e1){
                        tv.setApplyer("此用户已注销");
                    }
                }
            }
            // 关联流程信息
            ActProcess actProcess = actProcessService.get(tv.getProcDefId());
            if(actProcess!=null){
                tv.setProcessName(actProcess.getName());
                tv.setRouteName(actProcess.getRouteName());
            }
            // 关联业务key
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(tv.getProcInstId()).singleResult();
            tv.setBusinessKey(pi.getBusinessKey());
            ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
            if(actBusiness!=null){
                tv.setTableId(actBusiness.getTableId());
                EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                if(eventReport!=null){
                    tv.setEventType(eventReport.getEventType());
                    tv.setEventDescribe(eventReport.getEventDescribe());
                    tv.setLocality(eventReport.getLocality());
                    tv.setEventNum(eventReport.getEventNum());
                    tv.setFront(eventReport.getFront());
                    tv.setTaskEndTime(eventReport.getTaskEndTime());
                }
            }
            //关联上一节点审批意见
            List<HistoricTaskInstance> instances = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(tv.getProcInstId()).orderByHistoricTaskInstanceEndTime().asc().list();
            for (HistoricTaskInstance ht : instances){
                HistoricTaskVo htv = new HistoricTaskVo(ht);
                List<Comment> comments = taskService.getTaskComments(htv.getId(), "comment");
                if(comments!=null&&comments.size()>0){
                    tv.setComment(comments.get(0).getFullMessage());
                }else {
                    tv.setComment("没有上一节点");
                }
            }
            list.add(tv);
        });
        page.setContent(list);
        return new ResultUtil<Object>().setData(page);
    }

    @RequestMapping(value = "/doneList", method = RequestMethod.GET)
    @ApiOperation(value = "已办列表")
    public Result<Object> doneList(@RequestParam(required = false) String name,
                                   @RequestParam(required = false) String depId,
                                   @RequestParam(required = false) String categoryId,
                                   @RequestParam(required = false) Integer priority,
                                   @RequestParam(required = false) String locality,
                                   @RequestParam(required = false) String eventDescribe,
                                   @RequestParam(required = false) String eventType,
                                   @RequestParam(required = false) String eventNum,
                                   @RequestParam(required = false) String depPineId,
                                   @ModelAttribute SearchVo searchVo,
                                   @ModelAttribute PageVo pageVo){

        ActPage<HistoricTaskVo> page = new ActPage<HistoricTaskVo>();
        List<HistoricTaskVo> list = new ArrayList<>();

        String userId = securityUtil.getCurrUser().getId();
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().or().taskCandidateUser(userId).
                taskAssignee(userId).endOr().finished();

        // 多条件搜索
        if("createTime".equals(pageVo.getSort())&&"asc".equals(pageVo.getOrder())){
            query.orderByHistoricTaskInstanceEndTime().asc();
        }else if("priority".equals(pageVo.getSort())&&"asc".equals(pageVo.getOrder())){
            query.orderByTaskPriority().asc();
        }else if("priority".equals(pageVo.getSort())&&"desc".equals(pageVo.getOrder())){
            query.orderByTaskPriority().desc();
        }else if("duration".equals(pageVo.getSort())&&"asc".equals(pageVo.getOrder())){
            query.orderByHistoricTaskInstanceDuration().asc();
        }else if("duration".equals(pageVo.getSort())&&"desc".equals(pageVo.getOrder())){
            query.orderByHistoricTaskInstanceDuration().desc();
        }else{
            query.orderByHistoricTaskInstanceEndTime().desc();
        }

        if(StrUtil.isNotBlank(categoryId)){
            query.taskCategory(categoryId);
        }
        if(priority!=null){
            query.taskPriority(priority);
        }
        //时间查询
        if(searchVo != null){
            if (StrUtil.isNotBlank(searchVo.getStartDate())){
                Date start = DateUtil.parse(searchVo.getStartDate());
                query.taskCompletedAfter(start);
            }
            if (StrUtil.isNotBlank(searchVo.getEndDate())){
                Date end = DateUtil.parse(searchVo.getEndDate());
                query.taskCompletedBefore(DateUtil.endOfDay(end));
            }
        }else{
            Date da = new Date();//获取当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(da);//把当前时间赋给日历
            calendar.add(calendar.MONTH, -2); //设置为前2月 MONTH DAY_OF_MONTH
            da = calendar.getTime();//获取2个月前的时间
            query.taskCompletedAfter(DateUtil.endOfDay(da));
        }

        List<HistoricTaskInstance> taskLists =  query.list();
        List<HistoricTaskInstance> taskInstances1 =  new ArrayList<>();
        //部门查询
        if(StrUtil.isNotBlank(depId)){
            for(int i = 0;i<taskLists.size();i++){
                HistoricTaskVo hvt = new HistoricTaskVo(taskLists.get(i));
                List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForProcessInstance(hvt.getProcInstId());
                for(HistoricIdentityLink hik : identityLinks){
                    // 关联发起人
                    if("starter".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                        try {
                            if(depId.equals(userService.get(hik.getUserId()).getDepartmentId())){
                                taskInstances1.add(taskLists.get(i));
                            }
                        }catch (Exception e1){}
                    }
                }
            }
        }else{
            taskInstances1 = taskLists;
        }
        //上报人查询
        List<HistoricTaskInstance> taskInstances =  new ArrayList<>();
        if(StrUtil.isNotBlank(name)){
            for(int i = 0;i<taskInstances1.size();i++){
                HistoricTaskVo htv = new HistoricTaskVo(taskInstances1.get(i));
                List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForProcessInstance(htv.getProcInstId());
                for(HistoricIdentityLink hik : identityLinks){
                    // 关联发起人
                    if("starter".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                        try {
                            if(userService.get(hik.getUserId()).getUsername().contains(name)){
                                taskInstances.add(taskInstances1.get(i));
                            }
                        }catch (Exception e1){}

                    }
                }
            }
        }else{
            taskInstances = taskInstances1;
        }
        //发生地点
        List<HistoricTaskInstance> localityArr =  new ArrayList<>();
        if (StrUtil.isNotBlank(locality)){
            for (int i=0;i<taskInstances.size();i++){
                HistoricTaskVo htv = new HistoricTaskVo(taskInstances.get(i));
                HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(htv.getProcInstId()).singleResult();
                ActBusiness actBusiness = actBusinessService.get(hpi.getBusinessKey());
                EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                if (eventReport != null&&eventReport.getLocality() !=null&&eventReport.getLocality() != ""){
                    if (eventReport.getLocality().contains(locality)){
                        localityArr.add(taskInstances.get(i));
                    }
                }
            }
        }else {
            localityArr = taskInstances;
        }
        //事件编码
        List<HistoricTaskInstance> eventNumArr =  new ArrayList<>();
        if (StrUtil.isNotBlank(eventNum)){
            for (int i=0;i<localityArr.size();i++){
                HistoricTaskVo htv = new HistoricTaskVo(localityArr.get(i));
                HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(htv.getProcInstId()).singleResult();
                ActBusiness actBusiness = actBusinessService.get(hpi.getBusinessKey());
                EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                if (eventReport != null&&eventReport.getEventNum() !=null&&eventReport.getEventNum() !=""){
                    if (eventReport.getEventNum().contains(eventNum)){
                        eventNumArr.add(localityArr.get(i));
                    }
                }
            }
        }else {
            eventNumArr = localityArr;
        }
        //事件描述
        List<HistoricTaskInstance> eventDescribeArr =  new ArrayList<>();
        if (StrUtil.isNotBlank(eventDescribe)){
            for (int i=0;i<eventNumArr.size();i++){
                HistoricTaskVo htv = new HistoricTaskVo(eventNumArr.get(i));
                HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(htv.getProcInstId()).singleResult();
                ActBusiness actBusiness = actBusinessService.get(hpi.getBusinessKey());
                EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                if (eventReport != null&&eventReport.getEventDescribe() !=null &&eventReport.getEventDescribe() !=""){
                    if (eventReport.getEventDescribe().contains(eventDescribe)){
                        eventDescribeArr.add(eventNumArr.get(i));
                    }
                }
            }
        }else {
            eventDescribeArr = eventNumArr;
        }
        //事件类型
        List<HistoricTaskInstance> eventTypeArr =  new ArrayList<>();
        if (StrUtil.isNotBlank(eventType)){
            for (int i=0;i<eventDescribeArr.size();i++){
                HistoricTaskVo htv = new HistoricTaskVo(eventDescribeArr.get(i));
                HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(htv.getProcInstId()).singleResult();
                ActBusiness actBusiness = actBusinessService.get(hpi.getBusinessKey());
                EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                if (eventReport != null&&eventReport.getEventType() !=null &&eventReport.getEventType() !=""){
                    if (eventReport.getEventType().equals(eventType)){
                        eventTypeArr.add(eventDescribeArr.get(i));
                    }
                }
            }
        }else {
            eventTypeArr = eventDescribeArr;
        }
        //下派部门
        List<HistoricTaskInstance> depPineIdArr =  new ArrayList<>();
        if (StrUtil.isNotBlank(depPineId)){
            for (int i=0;i<eventTypeArr.size();i++){
                //获取此事件所有节点
                List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                        .processInstanceId(eventTypeArr.get(i).getProcessInstanceId()).orderByHistoricTaskInstanceEndTime().asc().list();
                List<String> departmentIds = new LinkedList<>();
                for (HistoricTaskInstance task : taskList){
                    List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForTask(task.getId());
                    for(HistoricIdentityLink hik : identityLinks){
                        // 关联候选用户（分配的候选用户审批人）
                        if("candidate".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                            //获取下派用户的部门
                            String departmentId = "";
                            try {
                                departmentId = userService.get(hik.getUserId()).getDepartmentId();
                                departmentIds.add(departmentId);
                            }catch (Exception e1){}
                        }
                    }
                }
                for (int j=0;j<departmentIds.size();j++){
                    if (depPineId.equals(departmentIds.get(j))){
                        depPineIdArr.add(eventTypeArr.get(i));
                        break;
                    }
                }
            }
        }else {
            depPineIdArr = eventTypeArr;
        }

        page.setTotalElements((long) depPineIdArr.size());
        int first =  (pageVo.getPageNumber()-1) * pageVo.getPageSize();
        int end = depPineIdArr.size();
        if((first+pageVo.getPageSize())<end){
            end = first+pageVo.getPageSize();
        }
        List<HistoricTaskInstance> taskList = depPineIdArr.subList(first,end);

       /* page.setTotalElements((long) taskInstances.size());
        int first =  (pageVo.getPageNumber()-1) * pageVo.getPageSize();
        int end = taskInstances.size();
        if((first+pageVo.getPageSize())<end){
            end = first+pageVo.getPageSize();
        }
        List<HistoricTaskInstance> taskList = taskInstances.subList(first,end);*/
        // 转换vo
        taskList.forEach(e -> {
            HistoricTaskVo htv = new HistoricTaskVo(e);
            // 关联委托人
            if(StrUtil.isNotBlank(htv.getOwner())){
                htv.setOwner(userService.get(htv.getOwner()).getUsername());
            }
            List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForProcessInstance(htv.getProcInstId());
            for(HistoricIdentityLink hik : identityLinks){
                // 关联发起人
                if("starter".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                    try {
                        htv.setApplyer(userService.get(hik.getUserId()).getUsername());
                    }catch (Exception e1){
                        htv.setApplyer("此用户已注销");
                    }
                }
            }
            // 关联审批意见
            List<Comment> comments = taskService.getTaskComments(htv.getId(), "comment");
            if(comments!=null&&comments.size()>0){
                htv.setComment(comments.get(0).getFullMessage());
            }
            // 关联流程信息
            ActProcess actProcess = actProcessService.get(htv.getProcDefId());
            if(actProcess!=null){
                htv.setProcessName(actProcess.getName());
                htv.setRouteName(actProcess.getRouteName());
            }
            // 关联业务key
            HistoricProcessInstance hpi = historyService.createHistoricProcessInstanceQuery().processInstanceId(htv.getProcInstId()).singleResult();
            htv.setBusinessKey(hpi.getBusinessKey());
            ActBusiness actBusiness = actBusinessService.get(hpi.getBusinessKey());
            if(actBusiness!=null){
                htv.setTableId(actBusiness.getTableId());
                htv.setStatus(actBusiness.getStatus());
                EventReport eventReport = eventReportService.get(actBusiness.getTableId());
                if(eventReport!=null){
                    htv.setEventType(eventReport.getEventType());
                    htv.setEventDescribe(eventReport.getEventDescribe());
                    htv.setLocality(eventReport.getLocality());
                    htv.setEventNum(eventReport.getEventNum());
                    htv.setFront(eventReport.getFront());
                    htv.setLater(eventReport.getLater());
                }
            }

            list.add(htv);
        });
        page.setContent(list);
        return new ResultUtil<Object>().setData(page);
    }

    @RequestMapping(value = "/historicFlow/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "流程流转历史")
    public Result<Object> historicFlow(@ApiParam("流程实例id") @PathVariable String id){

        List<HistoricTaskVo> list = new ArrayList<>();

        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(id).orderByHistoricTaskInstanceEndTime().asc().list();

        // 转换vo
        taskList.forEach(e -> {
            HistoricTaskVo htv = new HistoricTaskVo(e);
            List<Assignee> assignees = new ArrayList<>();
            // 关联分配人（委托用户时显示该人）
            if(StrUtil.isNotBlank(htv.getAssignee())){
                String username = userService.get(htv.getAssignee()).getUsername();
                htv.setAssignee(username);
                assignees.add(new Assignee(username, true));
            }
            List<HistoricIdentityLink> identityLinks = historyService.getHistoricIdentityLinksForTask(e.getId());
            StringBuilder candidateBuilder = new StringBuilder();
            // 获取实际审批用户id
            String userId = iHistoryIdentityService.findUserIdByTypeAndTaskId(ActivitiConstant.EXECUTOR_TYPE, e.getId());
            for(HistoricIdentityLink hik : identityLinks){
                // 关联候选用户（分配的候选用户审批人）
                if("candidate".equals(hik.getType())&&StrUtil.isNotBlank(hik.getUserId())){
                    String username = "";
                    try {
                        username = userService.get(hik.getUserId()).getUsername();
                    }catch (Exception e1){
                        username = "此用户已注销";
                    }
                    Assignee assignee = new Assignee(username, false);
                    if(StrUtil.isNotBlank(userId)&&userId.equals(hik.getUserId())){
                        assignee.setIsExecutor(true);
                        username+="(实际审批)";
                    }
                    if(StrUtil.isBlank(candidateBuilder.toString())){
                        candidateBuilder.append(username);
                    }else{
                        candidateBuilder.append("、" + username);
                    }
                    assignees.add(assignee);
                }
            }
            if(StrUtil.isBlank(htv.getAssignee())&&StrUtil.isNotBlank(candidateBuilder.toString())){
                htv.setAssignee(candidateBuilder.toString());
                htv.setAssignees(assignees);
            }
            // 关联审批意见
            List<Comment> comments = taskService.getTaskComments(htv.getId(), "comment");
            if(comments!=null&&comments.size()>0){
                htv.setComment(comments.get(0).getFullMessage());
            }
            list.add(htv);
        });
        return new ResultUtil<Object>().setData(list);
    }

    @RequestMapping(value = "/pass", method = RequestMethod.POST)
    @ApiOperation(value = "任务节点审批通过")
    public Result<Object> pass(@ApiParam("任务id") @RequestParam String id,
                               @ApiParam("流程实例id") @RequestParam String procInstId,
                               @ApiParam("下个节点审批人") @RequestParam(required = false) String[] assignees,
                               @ApiParam("优先级") @RequestParam(required = false) Integer priority,
                               @ApiParam("意见评论") @RequestParam(required = false) String comment,
                               @ApiParam("图片上传") @RequestParam(required = false) String later,
                               @ApiParam("按钮权限") @RequestParam(required = false) String buttonType,
                               @ApiParam("是否发送站内消息") @RequestParam(defaultValue = "false") Boolean sendMessage,
                               @ApiParam("是否发送短信通知") @RequestParam(defaultValue = "false") Boolean sendSms,
                               @ApiParam("是否发送邮件通知") @RequestParam(defaultValue = "false") Boolean sendEmail){

        if(StrUtil.isBlank(comment)){
            comment = "";
        }

        taskService.addComment(id, procInstId, comment);
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        Task task = taskService.createTaskQuery().taskId(id).singleResult();
        if(StrUtil.isNotBlank(task.getOwner())&&!("RESOLVED").equals(task.getDelegationState().toString())){
            // 未解决的委托任务 先resolve
            taskService.resolveTask(id);
        }
        //互斥网关按钮操作
        Map map = new HashMap();
        map.put("type", buttonType);
        taskService.complete(id,map);
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(procInstId).list();
        // 判断下一个节点
        if(tasks!=null&&tasks.size()>0){
            for(Task t : tasks){
                if(assignees==null||assignees.length<1){
                    // 如果分配审批人为空 设置默认审批用户
                    List<User> users = actProcessService.getNode(t.getTaskDefinitionKey()).getUsers();
                    for(User user : users){
                        taskService.addCandidateUser(t.getId(), user.getId());
                        // 异步发消息
                        messageUtil.sendActMessage(user.getId(), ActivitiConstant.MESSAGE_TODO_CONTENT, sendMessage, sendSms, sendEmail);
                    }
                }
                for(String assignee : assignees){
                    taskService.addCandidateUser(t.getId(), assignee);
                    // 异步发消息
                    messageUtil.sendActMessage(assignee, ActivitiConstant.MESSAGE_TODO_CONTENT, sendMessage, sendSms, sendEmail);
                }
                if(priority!=null){
                    taskService.setPriority(t.getId(), priority);
                }
            }
        } else {
            ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
            actBusiness.setStatus(ActivitiConstant.STATUS_FINISH);
            actBusiness.setResult(ActivitiConstant.RESULT_PASS);
            actBusinessService.update(actBusiness);
            // 异步发消息
            messageUtil.sendActMessage(actBusiness.getUserId(), ActivitiConstant.MESSAGE_PASS_CONTENT, sendMessage, sendSms, sendEmail);
        }
        // 记录实际审批人员
        iHistoryIdentityService.insert(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()),
                ActivitiConstant.EXECUTOR_TYPE, securityUtil.getCurrUser().getId(), id, procInstId);
        //办结图片上传
        if (null != later&&!"".equals(later)){
            ActBusiness byProcInstId = actBusinessService.getByProcInstId(procInstId);
            EventReport eventReport = eventReportService.get(byProcInstId.getTableId());
            eventReport.setLater(later);
            eventReportService.save(eventReport);
        }
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/passAll/{ids}", method = RequestMethod.POST)
    @ApiOperation(value = "批量通过")
    public Result<Object> passAll(@ApiParam("任务ids") @PathVariable String[] ids,
                                  @ApiParam("是否发送站内消息") @RequestParam(defaultValue = "false") Boolean sendMessage,
                                  @ApiParam("是否发送短信通知") @RequestParam(defaultValue = "false") Boolean sendSms,
                                  @ApiParam("是否发送邮件通知") @RequestParam(defaultValue = "false") Boolean sendEmail){

        for(String id:ids){
            Task task = taskService.createTaskQuery().taskId(id).singleResult();
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
            if(StrUtil.isNotBlank(task.getOwner())&&!("RESOLVED").equals(task.getDelegationState().toString())){
                // 未解决的委托任务 先resolve
                taskService.resolveTask(id);
            }
            taskService.complete(id);
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).list();
            // 判断下一个节点
            if(tasks!=null&&tasks.size()>0){
                for(Task t : tasks){
                    List<User> users = actProcessService.getNode(t.getTaskDefinitionKey()).getUsers();
                    for(User user : users){
                        taskService.addCandidateUser(t.getId(), user.getId());
                        // 异步发消息
                        messageUtil.sendActMessage(user.getId(), ActivitiConstant.MESSAGE_TODO_CONTENT, sendMessage, sendSms, sendEmail);
                    }
                    taskService.setPriority(t.getId(), task.getPriority());
                }
            } else {
                ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
                actBusiness.setStatus(ActivitiConstant.STATUS_FINISH);
                actBusiness.setResult(ActivitiConstant.RESULT_PASS);
                actBusinessService.update(actBusiness);
                // 异步发消息
                messageUtil.sendActMessage(actBusiness.getUserId(), ActivitiConstant.MESSAGE_PASS_CONTENT, sendMessage, sendSms, sendEmail);
            }
            // 记录实际审批人员
            iHistoryIdentityService.insert(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()),
                    ActivitiConstant.EXECUTOR_TYPE, securityUtil.getCurrUser().getId(), id, pi.getId());
        }
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/getBackList/{procInstId}", method = RequestMethod.GET)
    @ApiOperation(value = "获取可返回的节点")
    public Result<Object> getBackList(@PathVariable String procInstId){
        List<HistoricTaskVo> list = new ArrayList<>();
        List<HistoricTaskInstance> historicTaskInstanceList = new ArrayList<>();
        List<HistoricTaskInstance> taskInstanceList = historyService.createHistoricTaskInstanceQuery().processInstanceId(procInstId)
                .list();
        if(taskInstanceList != null && taskInstanceList.size()>0){
            //按创建时间排序
                Collections.sort(taskInstanceList,new Comparator<HistoricTaskInstance>(){
                @Override
                public int compare(HistoricTaskInstance o1, HistoricTaskInstance o2) {
                    int flag = o1.getCreateTime().compareTo(o2.getCreateTime());
                    return flag;
                }
            });
            int i = taskInstanceList.size();
            HistoricTaskInstance historicTaskInstance = taskInstanceList.get(i-1);
            for (int j = 0;j<i;j++){
                HistoricTaskInstance historicTaskInstance1 = taskInstanceList.get(j);
                if (historicTaskInstance1.getTaskDefinitionKey() != null && historicTaskInstance1.getTaskDefinitionKey().equals(historicTaskInstance.getTaskDefinitionKey())) {
                    break;
                }
                historicTaskInstanceList.add(historicTaskInstance1);
            }
        }
        historicTaskInstanceList.forEach(e -> {
            HistoricTaskVo htv = new HistoricTaskVo(e);
            list.add(htv);
        });
        // 去重
        LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
        List<HistoricTaskVo> newList = new ArrayList<>();
        list.forEach(e->{
            if(set.add(e.getName())){
                newList.add(e);
            }
        });
        //审批流程越级上报下派限制
        if(existRoleName("ROLE_区河长办")){//区级河长驳回限制操作
            List<Department> getdep = eventReportMapper.getdep();
            for(int i=0;i<newList.size();i++){
                if (!"镇级河长办".equals(newList.get(i).getName())){
                    newList.remove(i);
                    i--;
                }else {
                    newList.get(i).setDepartments(getdep);
                }

            }
        }else if (existRoleName("ROLE_流域河长办")) {
            for(int i=0;i<newList.size();i++){
                String name = newList.get(i).getName();
                if ("区河长办".equals(newList.get(i).getName())){
                    newList.remove(i);
                    i--;
                }
            }
        }/*else if (existRoleName("ROLE_镇河长办")){//镇级河长驳回限制操作
            for(int i=0;i<newList.size();i++){
                if ("流域河长办".equals(newList.get(i).getName())){
                    newList.remove(i);
                    i--;
                }
            }
        }else if (existRoleName("ROLE_村河长")){ //村级河长驳回限制操作
            for(int i=0;i<newList.size();i++){
                if ("流域河长办".equals(newList.get(i).getName())){
                    newList.remove(i);
                    i--;
                }
            }
        } */
        return new ResultUtil<Object>().setData(newList);
    }


    @RequestMapping(value = "/backToTask", method = RequestMethod.POST)
    @ApiOperation(value = "任务节点审批驳回至指定历史节点")
    public Result<Object> backToTask(@ApiParam("任务id") @RequestParam String id,
                                     @ApiParam("驳回指定节点key") @RequestParam String backTaskKey,
                                     @ApiParam("流程实例id") @RequestParam String procInstId,
                                     @ApiParam("流程定义id") @RequestParam String procDefId,
                                     @ApiParam("原节点审批人") @RequestParam(required = false) String[] assignees,
                                     @ApiParam("优先级") @RequestParam(required = false) Integer priority,
                                     @ApiParam("意见评论") @RequestParam(required = false) String comment,
                                     @ApiParam("是否发送站内消息") @RequestParam(defaultValue = "false") Boolean sendMessage,
                                     @ApiParam("是否发送短信通知") @RequestParam(defaultValue = "false") Boolean sendSms,
                                     @ApiParam("是否发送邮件通知") @RequestParam(defaultValue = "false") Boolean sendEmail){


        if(StrUtil.isBlank(comment)){
            comment = "";
        }
        taskService.addComment(id, procInstId, comment);
        // 取得流程定义
        ProcessDefinitionEntity definition = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(procDefId);
        // 获取历史任务的Activity
        ActivityImpl hisActivity = definition.findActivity(backTaskKey);
        // 实现跳转
        managementService.executeCommand(new JumpTask(procInstId, hisActivity.getId()));
        // 重新分配原节点审批人
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(procInstId).list();
        if(tasks!=null&&tasks.size()>0){
            tasks.forEach(e->{
                for(String assignee:assignees){
                    taskService.addCandidateUser(e.getId(), assignee);
                    // 异步发消息
                    messageUtil.sendActMessage(assignee, ActivitiConstant.MESSAGE_TODO_CONTENT, sendMessage, sendSms, sendEmail);
                }
                if(priority!=null){
                    taskService.setPriority(e.getId(), priority);
                }
            });
        }
        // 记录实际审批人员
        iHistoryIdentityService.insert(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()),
                ActivitiConstant.EXECUTOR_TYPE, securityUtil.getCurrUser().getId(), id, procInstId);
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    public class JumpTask implements Command<ExecutionEntity> {

        private String procInstId;
        private String activityId;

        public JumpTask(String procInstId, String activityId) {
            this.procInstId = procInstId;
            this.activityId = activityId;
        }

        @Override
        public ExecutionEntity execute(CommandContext commandContext) {

            ExecutionEntity executionEntity = commandContext.getExecutionEntityManager().findExecutionById(procInstId);
            executionEntity.destroyScope("backed");
            ProcessDefinitionImpl processDefinition = executionEntity.getProcessDefinition();
            ActivityImpl activity = processDefinition.findActivity(activityId);
            executionEntity.executeActivity(activity);

            return executionEntity;
        }
    }

    @RequestMapping(value = "/back", method = RequestMethod.POST)
    @ApiOperation(value = "任务节点审批驳回至发起人")
    public Result<Object> back(@ApiParam("任务id") @RequestParam String id,
                               @ApiParam("流程实例id") @RequestParam String procInstId,
                               @ApiParam("意见评论") @RequestParam(required = false) String comment,
                               @ApiParam("是否发送站内消息") @RequestParam(defaultValue = "false") Boolean sendMessage,
                               @ApiParam("是否发送短信通知") @RequestParam(defaultValue = "false") Boolean sendSms,
                               @ApiParam("是否发送邮件通知") @RequestParam(defaultValue = "false") Boolean sendEmail){


        if(StrUtil.isBlank(comment)){
            comment = "";
        }
        taskService.addComment(id, procInstId, comment);
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
        // 删除流程实例
        runtimeService.deleteProcessInstance(procInstId, "backed");
        ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
        actBusiness.setStatus(ActivitiConstant.STATUS_FINISH);
        actBusiness.setResult(ActivitiConstant.RESULT_FAIL);
        actBusinessService.update(actBusiness);
        // 异步发消息
        messageUtil.sendActMessage(actBusiness.getUserId(), ActivitiConstant.MESSAGE_BACK_CONTENT, sendMessage, sendSms, sendEmail);
        // 记录实际审批人员
        iHistoryIdentityService.insert(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()),
                ActivitiConstant.EXECUTOR_TYPE, securityUtil.getCurrUser().getId(), id, procInstId);
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/backAll/{procInstIds}", method = RequestMethod.POST)
    @ApiOperation(value = "批量驳回至发起人")
    public Result<Object> backAll(@ApiParam("流程实例ids") @PathVariable String[] procInstIds,
                                  @ApiParam("是否发送站内消息") @RequestParam(defaultValue = "false") Boolean sendMessage,
                                  @ApiParam("是否发送短信通知") @RequestParam(defaultValue = "false") Boolean sendSms,
                                  @ApiParam("是否发送邮件通知") @RequestParam(defaultValue = "false") Boolean sendEmail){

        for(String procInstId:procInstIds){
            // 记录实际审批人员
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(procInstId).list();
            tasks.forEach(t->{
                iHistoryIdentityService.insert(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()),
                        ActivitiConstant.EXECUTOR_TYPE, securityUtil.getCurrUser().getId(), t.getId(), procInstId);
            });
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
            // 删除流程实例
            runtimeService.deleteProcessInstance(procInstId, ActivitiConstant.BACKED_FLAG);
            ActBusiness actBusiness = actBusinessService.get(pi.getBusinessKey());
            actBusiness.setStatus(ActivitiConstant.STATUS_FINISH);
            actBusiness.setResult(ActivitiConstant.RESULT_FAIL);
            actBusinessService.update(actBusiness);
            // 异步发消息
            messageUtil.sendActMessage(actBusiness.getUserId(), ActivitiConstant.MESSAGE_BACK_CONTENT, sendMessage, sendSms, sendEmail);
        }
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/delegate", method = RequestMethod.POST)
    @ApiOperation(value = "委托他人代办")
    public Result<Object> delegate(@ApiParam("任务id") @RequestParam String id,
                                   @ApiParam("委托用户id") @RequestParam String userId,
                                   @ApiParam("流程实例id") @RequestParam String procInstId,
                                   @ApiParam("意见评论") @RequestParam(required = false) String comment,
                                   @ApiParam("是否发送站内消息") @RequestParam(defaultValue = "false") Boolean sendMessage,
                                   @ApiParam("是否发送短信通知") @RequestParam(defaultValue = "false") Boolean sendSms,
                                   @ApiParam("是否发送邮件通知") @RequestParam(defaultValue = "false") Boolean sendEmail){

        if(StrUtil.isBlank(comment)){
            comment = "";
        }
        taskService.addComment(id, procInstId, comment);
        taskService.delegateTask(id, userId);
        taskService.setOwner(id, securityUtil.getCurrUser().getId());
        // 异步发消息
        messageUtil.sendActMessage(userId, ActivitiConstant.MESSAGE_DELEGATE_CONTENT, sendMessage, sendSms, sendEmail);
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除任务")
    public Result<Object> delete(@ApiParam("任务id") @PathVariable String[] ids,
                                 @ApiParam("原因") @RequestParam(required = false) String reason){

        if(StrUtil.isBlank(reason)){
            reason = "";
        }
        for(String id : ids){
            taskService.deleteTask(id, reason);
        }
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/deleteHistoric/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "删除任务历史")
    public Result<Object> deleteHistoric(@ApiParam("任务id") @PathVariable String[] ids){

        for(String id : ids){
            historyService.deleteHistoricTaskInstance(id);
        }
        return new ResultUtil<Object>().setSuccessMsg("操作成功");
    }

    @RequestMapping(value = "/getSjCount", method = RequestMethod.GET)
    @ApiOperation(value = "获取事件统计总数")
    public Result<Integer> getSjCount(){
      Integer count = iActService.findSjCount();
        return new ResultUtil<Integer>().setData(count);
    }

    @RequestMapping(value = "/getSjCharts", method = RequestMethod.GET)
    @ApiOperation(value = "事件统计图表")
    public Result<List<Map>> sjCharts(){
        return new ResultUtil<List<Map>>().setData(iActService.findSjCharts());
    }

    @RequestMapping(value = "/getTime", method = RequestMethod.GET)
    @ApiOperation(value = "获取基层河长数据")
    public Result<String> getTime(){
        SimpleDateFormat temp=new SimpleDateFormat("yyyy");
        String format = temp.format(new Date());
        return new ResultUtil<String>().setData(format);
    }
    @RequestMapping(value = "/getMonth", method = RequestMethod.GET)
    @ApiOperation(value = "获取基层河长月")
    public Result<String> getMonth(){
        SimpleDateFormat temp=new SimpleDateFormat("MM");
        String format = temp.format(new Date());
        return new ResultUtil<String>().setData(format);
    }
    @RequestMapping(value = "/getjcAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取基层河长发现问题数")
    public Result<Integer> getjcAll(){
        SimpleDateFormat temp=new SimpleDateFormat("yyyy");
        String format = temp.format(new Date());
        SimpleDateFormat temp2=new SimpleDateFormat("MM");
        String format2 = temp2.format(new Date());
        String end = "'%"+format+"-"+format2+"%'";
        Integer jcAll = iActService.getjcAll(end);

        return new ResultUtil<Integer>().setData(jcAll);
    }
    @RequestMapping(value = "/getzgAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取基层河长解决问题数")
    public Result<Integer> getzgAll(){
        SimpleDateFormat temp=new SimpleDateFormat("yyyy");
        String format = temp.format(new Date());
        SimpleDateFormat temp2=new SimpleDateFormat("MM");
        String format2 = temp2.format(new Date());
        String end = "'%"+format+"-"+format2+"%'";
        System.out.println(end);
        Integer zgAll = iActService.getzgAll(end);
        return new ResultUtil<Integer>().setData(zgAll);
    }

    @RequestMapping(value = "/getRectify", method = RequestMethod.GET)
    @ApiOperation(value = "获取基层河长解决问题率")
    public Result<String> getRectify(){
        SimpleDateFormat temp=new SimpleDateFormat("yyyy");
        String format = temp.format(new Date());
        SimpleDateFormat temp2=new SimpleDateFormat("MM");
        String format2 = temp2.format(new Date());
        String end = "'%"+format+"-"+format2+"%'";
        Integer zgAll = iActService.getzgAll(end);
        Integer jcAll = iActService.getjcAll(end);
        String rectify= "0.00";
        if(zgAll!=0&&jcAll!=0){
            Double zg = zgAll*1.00;
            Double jc= jcAll*1.00;
            NumberFormat nf = new DecimalFormat("#0.00");
            rectify = nf.format(zg /jc   *100);
        }else{

        }
        return new ResultUtil<String>().setData(rectify);
    }


    @RequestMapping(value = "/getwtCharts", method = RequestMethod.GET)
    @ApiOperation(value = "发现问题数及整改统计图表")
    public Result<List<Map>> getwtCharts(){
        SimpleDateFormat temp=new SimpleDateFormat("yyyy");
        String format = temp.format(new Date());
        SimpleDateFormat temp2=new SimpleDateFormat("MM");
        String format2 = temp2.format(new Date());
        String end = "'%"+format+"-"+format2+"%'";
        return new ResultUtil<List<Map>>().setData(iActService.findwtCharts(end));
    }
    /**
     * 当前用户是否有此角色
     * @param roleName
     * @return
     */
    private boolean existRoleName(String roleName){
        if(roleName ==null){
            return false;
        }
        //获取当前登陆用户
        User currUser = securityUtil.getCurrUser();
        String nameRole = null;
        for (Role role : currUser.getRoles()){
            if(roleName.equals(role.getName())){
                nameRole = role.getName();
            }
        }
        return nameRole != null;
    }

    //获取整改数量
    @RequestMapping(value = "/getJJCount", method = RequestMethod.GET)
    @ApiOperation(value = "获取整改数量")
    public Result<String> getJJCount(){
        String s = iActService.getJJAll();
        return new ResultUtil<String>().setData(s);
    }

}
